package com.lizixin.service.impl;


import com.lizixin.dao.UserInfoMapper;
import com.lizixin.pojo.Page;
import com.lizixin.pojo.UserInfo;
import com.lizixin.pojo.UserInfoExample;
import com.lizixin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 黎子新 on 2017/6/14.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public List<UserInfo> getAllUser() {
       return userInfoMapper.selectByExample(null);
}

    @Override
    public void deleteUser(Integer id) {

        userInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(UserInfo user) {
        userInfoMapper.updateByPrimaryKey(user);
    }

    @Override
    public UserInfo getLoginUser(String username,Integer password) {

        UserInfoExample example = new UserInfoExample();
        UserInfoExample.Criteria criteria = example.createCriteria();

        criteria.andUnameEqualTo(username);
        criteria.andUnumberEqualTo(password);

         List<UserInfo> list=   userInfoMapper.selectByExample(example);

         return list.get(0);
    }

    @Override
    public UserInfo getUserById(Integer id) {
       return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer addUser(UserInfo userInfo) {
        return userInfoMapper.insert(userInfo);
    }


    public void showUserInfoByPage(HttpServletRequest request, Model model) {
        String pageNow=request.getParameter("pageNow");
        Page page=null;
        List<UserInfo> list=new ArrayList<UserInfo>();
        int totalCount=(int)userInfoMapper.getItemsCount();
        if (pageNow!=null){
            page=new Page(Integer.parseInt(pageNow),totalCount);
            list=userInfoMapper.selectItemsByPage(page.getStartPos(),page.getPageSize());
        }else{
            page=new Page(1,totalCount);
            list=userInfoMapper.selectItemsByPage(page.getStartPos(),page.getPageSize());
        }
        model.addAttribute("users",list);
        model.addAttribute("page",page);
    }

    @Override
    public long getUserInfoCount() {

        return userInfoMapper.getItemsCount();
    }

}
